import { Color3, Engine, SpriteManager, Vector3, Sprite, Scene, ArcRotateCamera, PointLight, StandardMaterial, Texture, ShaderMaterial, IAnimationKey } from 'babylonjs'

// 动作
export class Demo5 {
  private dom: HTMLCanvasElement
  private engine: Engine
  private scene: Scene
  private camera: ArcRotateCamera

  constructor(dom: HTMLCanvasElement) {
    this.dom = dom
    this.engine = new Engine(this.dom, true)  // 设置引擎
    this.scene = new Scene(this.engine)   // 创建场景
    this.camera = new ArcRotateCamera("Camera", 1, 0.8, 100, Vector3.Zero(), this.scene); // 创建相机
    this.camera.attachControl(this.dom, false)  // 把相机放到画布

    // 创建sprite管理器以优化GPU资源
    // 参数：名称，imgurl，容量
    const spriteManagerTrees = new SpriteManager("treesManager", "/1.jpg", 600, 400, this.scene);

    // 创建2000个数 随机定位
    for (var i = 0; i < 2000; i++) {
      const tree = new Sprite("tree", spriteManagerTrees);
      tree.position.x = Math.random() * 100 - 50;
      tree.position.z = Math.random() * 100 - 50;
      tree.isPickable = true;

      //Some "dead" trees
      if (Math.round(Math.random() * 5) === 0) {
        tree.angle = Math.PI * 90 / 180;
        tree.position.y = -0.3;
      }
    }


    // 创建动画管理
    const spriteManagerPlayer = new SpriteManager("playerManager", "/people.png", 213, 509, this.scene);

    // 动画播放
    const player = new Sprite("player", spriteManagerPlayer);
    player.playAnimation(0, 40, true, 100);
    player.position.y = -0.3;
    player.size = 0.3;
    player.isPickable = true;


    const player2 = new Sprite("player2", spriteManagerPlayer);
    player2.stopAnimation(); // Not animated
    player2.cellIndex = 2; // Going to frame number 2
    player2.position.y = -0.3;
    player2.position.x = 1;
    player2.size = 0.3;
    player2.invertU = false; //Change orientation
    player2.isPickable = true;


    spriteManagerTrees.isPickable = true;
    spriteManagerPlayer.isPickable = true;

    const that = this;

    this.scene.onPointerDown = function (evt) {
      const pickResult = that.scene.pickSprite(this.pointerX, this.pointerY);
      if (pickResult && pickResult.hit && pickResult.pickedSprite) {
        pickResult.pickedSprite.angle += 0.5;
      }
    };

    window.addEventListener('resize', () => {
      this.engine.resize();
    })
  }

  render() {
    // 引擎渲染场景
    this.engine.runRenderLoop(() => {
      this.scene.render()
    })
  }
}


